/*
 * Copyright 2009 Original Author(s)
 * 
 * This file is part of Kommando
 * 
 * Kommando is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Kommando is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Kommando.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.kommando.filesystem;

import java.awt.Image;
import java.io.File;
import java.lang.reflect.Method;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.filechooser.FileSystemView;

import org.kommando.core.util.Assert;

/**
 * @author Peter De Bruycker
 */
public class FileSystemUtils {

    private FileSystemUtils() {
        // static class
    }

    /**
     * First try retrieving the icon using the ShellFolder, falling back to the {@link FileSystemView#getSystemIcon(File)} method.
     * <p>
     * Rationale: the ShellFolder can retrieve larger size icons, but is only available on the Sun VM.
     * 
     * @param file
     *            the file
     * @return the icon
     */
    public static Icon getIcon(File file) {
        Assert.argumentNotNull("file", file);
        Assert.isTrue("file doesn't exist", file.exists());

        try {
            Class<?> shellFolderClass = Class.forName("sun.awt.shell.ShellFolder");
            try {
                Method getShellFolderMethod = shellFolderClass.getMethod("getShellFolder", File.class);
                Method getIconMethod = shellFolderClass.getMethod("getIcon", Boolean.TYPE);
                Object shellFolder = getShellFolderMethod.invoke(null, file);
                Image iconImage = (Image) getIconMethod.invoke(shellFolder, true);
                return iconImage == null ? null : new ImageIcon(iconImage);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } catch (ClassNotFoundException e) {
            return FileSystemView.getFileSystemView().getSystemIcon(file);
        }
    }

}
